package cn.renxuan.repository;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import cn.renxuan.CommonUtil;

public class DBHelper {

    private static String dbUser;
    private static String dbPwd;
    private static String dbUrl;

    public static void RegisterDbInfo() throws Exception {
        String profileName = System.getenv("SPRING_PROFILES_ACTIVE");
        String jdbcConfigFileName = String.format("jdbc%s.properties",
                profileName == null || profileName.isBlank() ? "" : "-" + profileName);

        CommonUtil.printThreadLog("开始加载数据库配置文件：" + jdbcConfigFileName);
        // 如果没有配置文件，则使用默认的jdbc.properties

        // 读取本地数据库配置文件
        InputStream rs = DBHelper.class.getClassLoader().getResourceAsStream(jdbcConfigFileName);
        // 本地文件流加载到Properties对象中
        Properties ps = new Properties();
        ps.load(rs);

        // 读取配置jdbc配置文件中的
        dbUser = ps.getProperty("dbUser");
        dbPwd = ps.getProperty("dbPwd");
        dbUrl = ps.getProperty("dbUrl");
        String dbDriverName = ps.getProperty("dbDriverName");
        // new com.mysql.jdbc.Driver()
        // 加载数据库访问驱动
        Class.forName(dbDriverName);
    }

    /*
     * 获取数据库连接对象
     */
    public static Connection getConnection() throws Exception {

        // 获取数据库连接对象
        Connection conn = null;
        if (dbUrl != null && !dbUrl.isBlank() && dbUser != null && !dbUser.isBlank() && dbPwd != null
                && !dbPwd.isBlank()) {
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
        }
        return conn;
    }

}
